from django.http import HttpResponse, JsonResponse
import subprocess
from .models import CarParameter, CarPlate
import os
import signal

# 保存服务的pid，用于关闭服务的
close_server_pid = {
    'plate_server_pid': None,
    'wheel_computed_pid': None,
    'decision_pid': None
}
STATUS = False
PLATE_STATUS = False
WHEEL_STATUS = False
DECISION_STATUS = False


def index(request):
    global STATUS
    if close_server_pid['plate_server_pid'] or close_server_pid['wheel_computed_pid'] or close_server_pid['decision_pid']:
        STATUS = True
    else:
        STATUS = False
    data = {
        'code': 200,
        'msg': 'success',
        'data': {
            'status': STATUS
        }
    }
    return JsonResponse(data=data, json_dumps_params={'ensure_ascii': False})


def decision(request):
    global DECISION_STATUS
    if not DECISION_STATUS:
        s = subprocess.Popen('cd ../newc/gpu_video_recognize/expert_decision'
                             '&& python3 double_event_upgrade_decision.py', stdout=subprocess.PIPE, shell=True,
                             close_fds=True, preexec_fn=os.setsid)
        # print(s.pid)
        # os.killpg(s.pid, signal.SIGUSR1)
        close_server_pid['decision_pid'] = (s.pid, signal.SIGUSR1)

        # 此时 decision 已经开启服务，将其状态设置为 True
        # 这样操作就可以避免多次请求
        DECISION_STATUS = True

    msg = '我去！服务器又蹦了。。。。。！'
    if DECISION_STATUS:
        msg = 'decision 服务已经开启，不可重复开发, 如果要重新请求，请先关闭服务'

    data = {
        'code': 200,
        'msg': 'success',
        'data': {
            'status': DECISION_STATUS,
            'msg': msg
        }
    }
    return JsonResponse(data=data, json_dumps_params={'ensure_ascii': False})


def plate_server(request):
    global PLATE_STATUS
    if not PLATE_STATUS:
        s = subprocess.Popen('cd ../newc/gpu_video_recognize/expert_server'
                             '&& python3 plate_recognition_server.py', shell=True, stdout=subprocess.PIPE,
                             close_fds=True, preexec_fn=os.setsid)
        # print(s.pid)
        # os.killpg(s.pid, signal.SIGUSR1)
        close_server_pid['plate_server_pid'] = (s.pid, signal.SIGUSR1)

        # out = s.stdout.read()
        # print(type(out))
        # print(out.decode('utf-8'))
        PLATE_STATUS = True

    msg = '我去！服务器又蹦了。。。。。'
    if PLATE_STATUS:
        msg = 'platet 服务已经开启，不可重复开发, 如果要重新请求，请先关闭服务'

    data = {
        'code': 200,
        'msg': 'success',
        'data': {
            'status': PLATE_STATUS,
            'msg': msg
        }
    }

    return JsonResponse(data=data, json_dumps_params={'ensure_ascii': False})


def wheel_computed(request):
    global WHEEL_STATUS
    if not WHEEL_STATUS:
        s = subprocess.Popen('cd ../newc/gpu_video_recognize/expert_server'
                             '&& python3 thread_wheel_compute_server.py', shell=True, stdout=subprocess.PIPE,
                             close_fds=True, preexec_fn=os.setsid)
        # print(s.pid)
        # print(signal.SIGUSR1)
        # os.killpg(s.pid, signal.SIGUSR1)
        close_server_pid['wheel_computed_pid'] = (s.pid, signal.SIGUSR1)

        WHEEL_STATUS = True

    msg = '我去！服务器又蹦了。。。。。'
    if WHEEL_STATUS:
        msg = 'wheel 服务已经开启，不可重复开发, 如果要重新请求，请先关闭服务'

    data = {
        'code': 200,
        'msg': 'success',
        'data': {
            'status': WHEEL_STATUS,
            'msg': msg
        }
    }
    return JsonResponse(data=data, json_dumps_params={'ensure_ascii': False})


# 前端请求的url，返回项目需要的数据 length wheel_base plate  wheel_num
def car_info_base(request):
    # 默认使用 create_time 倒序排序，这样直接取值就是最新的值
    carInfo = CarParameter.objects.first()
    plate = CarPlate.objects.first()
    data = {
        'length': carInfo.car_length,
        'wheel_base': carInfo.wheel_base,
        'wheel_num': carInfo.wheel_num,
        'plate': plate.car_plate,
        'car_image': str(plate.picture_path).replace('/home/hadoop/Documents/car', ''),
        'car_image1': str(plate.picture_path1).replace('/home/hadoop/Documents/car', ''),
        'car_image2': str(plate.picture_path2).replace('/home/hadoop/Documents/car', ''),
        'car_image3': str(plate.picture_path3).replace('/home/hadoop/Documents/car', ''),
    }
    return JsonResponse({'code': 200, 'status': '', 'data': data})


def close_server(request):
    global PLATE_STATUS
    global WHEEL_STATUS
    global DECISION_STATUS
    print(close_server_pid)

    for key, process in close_server_pid.items():
        try:
            os.killpg(process[0], process[1])
        except Exception as e:
            pass

    # 服务器已经关闭，就将起清空
    close_server_pid['plate_server_pid'] = None
    close_server_pid['wheel_computed_pid'] = None
    close_server_pid['decision_pid'] = None

    # 服务器已经关闭，将其状态码设置为 False
    PLATE_STATUS = False
    WHEEL_STATUS = False
    DECISION_STATUS = False
    return JsonResponse(close_server_pid)
